﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CMP.ERP.Admin.ServiceReference1;
using System.Windows.Forms;
using System.Data;

namespace CMP.ERP.Admin.Controllers
{
    public class StockController : Controller
    {
        //
        // GET: /Stock/
        ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
        public ActionResult Stock_Show()
        {
            return View();
        }
        public ActionResult ShowStockFasle()
        {
            return Json(client.StockOrderInfoShowFalse().ToList(),JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 删除入库信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DelStockOrderInfoAndPurcurementByStockOrderID(int id)
        {
            List<int> listint = client.DelStockOrderInfo(id).ToList();
            int content = 0;
            foreach (int item in listint)
            {
                if (item == 1)
                {
                    content = 1;
                }
                else
                {
                    content = 0;
                    continue;
                }
            }
            if (content == 1)
            {
                return Content("<script>alert('删除成功！！！');location.href='/Stock/Stock_Show'</script>");
            }
            else
            {
                return Content("<script>alert('删除失败！！！');location.href='/Stock/Stock_Show'</script>");
            }
        }
        /// <summary>
        /// 导出excel
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowExcel()
        {
            Microsoft.Office.Interop.Excel.Application appexcel = new Microsoft.Office.Interop.Excel.Application();

            SaveFileDialog savefiledialog = new SaveFileDialog();

            System.Reflection.Missing miss = System.Reflection.Missing.Value;

            appexcel = new Microsoft.Office.Interop.Excel.Application();

            Microsoft.Office.Interop.Excel.Workbook workbookdata;

            Microsoft.Office.Interop.Excel.Worksheet worksheetdata;

            Microsoft.Office.Interop.Excel.Range rangedata;

            //设置对象不可见

            appexcel.Visible = false;

            System.Globalization.CultureInfo currentci = System.Threading.Thread.CurrentThread.CurrentCulture;

            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-us");

            workbookdata = appexcel.Workbooks.Add(miss);

            worksheetdata = (Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets.Add(miss, miss, miss, miss);

            //给工作表赋名称

            worksheetdata.Name = "采购入库单";
            DataTable dt = new DataTable();
            dt = client.GetExcel().Tables[0];

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                worksheetdata.Cells[1, i + 1] = dt.Columns[i].ColumnName.ToString();
            }

            //因为第一行已经写了表头，所以所有数据都应该从a2开始

            rangedata = worksheetdata.get_Range("a2", miss);

            Microsoft.Office.Interop.Excel.Range xlrang = null;

            //irowcount为实际行数，最大行

            int irowcount = dt.Rows.Count;

            int iparstedrow = 0, icurrsize = 0;

            //ieachsize为每次写行的数值，可以自己设置

            int ieachsize = 1000;

            //icolumnaccount为实际列数，最大列数

            int icolumnaccount = dt.Columns.Count;

            //在内存中声明一个ieachsize×icolumnaccount的数组，ieachsize是每次最大存储的行数，icolumnaccount就是存储的实际列数

            object[,] objval = new object[ieachsize, icolumnaccount];

            icurrsize = ieachsize;





            while (iparstedrow < irowcount)
            {

                if ((irowcount - iparstedrow) < ieachsize)

                    icurrsize = irowcount - iparstedrow;

                //用for循环给数组赋值

                for (int i = 0; i < icurrsize; i++)
                {

                    for (int j = 0; j < icolumnaccount; j++)

                        objval[i, j] = dt.Rows[i + iparstedrow][j].ToString();

                    System.Windows.Forms.Application.DoEvents();

                }

                string X = "A" + ((int)(iparstedrow + 2)).ToString();

                string col = "";

                if (icolumnaccount <= 26)
                {

                    col = ((char)('A' + icolumnaccount - 1)).ToString() + ((int)(iparstedrow + icurrsize + 1)).ToString();

                }

                else
                {

                    col = ((char)('A' + (icolumnaccount / 26 - 1))).ToString() + ((char)('A' + (icolumnaccount % 26 - 1))).ToString() + ((int)(iparstedrow + icurrsize + 1)).ToString();

                }

                xlrang = worksheetdata.get_Range(X, col);

                // 调用range的value2属性，把内存中的值赋给excel

                xlrang.Value2 = objval;

                iparstedrow = iparstedrow + icurrsize;

            }

            //保存工作表

            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlrang);

            xlrang = null;

            //调用方法关闭excel进程

            appexcel.Visible = true;
            GC.Collect();

            return Content("<script>alert('导出成功！！');location.href='/Stock/Stock_Show'</script>");
        }
        #region datatable导入excel
        //public static void DataTableToExcel(System.Data.DataTable dt, string saveFileName)
        //{
        //    if (dt == null) return;
        //    //-***************获取excel对象***************
        //    //  string saveFileName = "";
        //    TimeSpan dateBegin = new TimeSpan(DateTime.Now.Ticks);
        //    bool fileSaved = false;
        //    SaveFileDialog saveDialog = new SaveFileDialog();
        //    saveDialog.DefaultExt = "xls";
        //    saveDialog.Filter = "Excel文件|*.xls";
        //    saveDialog.FileName = "导入记录查询结果 " + DateTime.Today.ToString("yyyy-MM-dd");
        //    saveDialog.ShowDialog();
        //    saveFileName = saveDialog.FileName;
        //    if (saveFileName.IndexOf(":") < 0) return; //被点了取消
        //    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
        //    if (xlApp == null)
        //    {
        //        MessageBox.Show("无法启动Excel，可能您未安装Excel");
        //        return;
        //    }
        //    Microsoft.Office.Interop.Excel.Workbook workbook = xlApp.Workbooks.Add(true);
        //    Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
        //    Microsoft.Office.Interop.Excel.Range range;


            
        //    // 列索引，行索引，总列数，总行数                   
        //    int colIndex = 0;
        //    int RowIndex = 0;
        //    int colCount = dt.Columns.Count;
        //    int RowCount = dt.Rows.Count;


        //    // *****************获取数据*********************

        //    // 创建缓存数据
        //    object[,] objData = new object[RowCount+1, colCount];
        //    // 获取列标题
        //    for (int i = 0; i < dt.Columns.Count; i++)
        //    {
        //        objData[RowIndex, colIndex++] = dt.Columns[i].Caption; // dgv.Columns[i].HeaderText;
        //    }

        //    // 获取具体数据
        //    for (RowIndex = 0; RowIndex < RowCount; RowIndex++)
        //    {
        //        for (colIndex = 0; colIndex < colCount; colIndex++)
        //        {
        //            objData[RowIndex+1, colIndex] = dt.Rows[RowIndex][colIndex];
        //        }

        //    }


        //    //*******************设置输出格式******************************

        //    //设置顶部説明   合并的单元格
        //    range = worksheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, colCount]);
        //    range.MergeCells = true;
        //    range.RowHeight = 38;
        //    range.Font.Bold = true;
        //    range.Font.Size = 14;
        //    range.Font.ColorIndex = 10;//字体颜色
        //    xlApp.ActiveCell.FormulaR1C1 = "导入记录查询结果";

        //    //特殊数字格式
        //    //range = worksheet.get_Range(xlApp.Cells[2, colCount], xlApp.Cells[RowCount, colCount]);


        //    xlApp.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
        //    range = worksheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[2, colCount]);

        //    range.Font.Bold = true;
        //    range.RowHeight = 20;


        //    //********************* 写入Excel*******************

        //    range = worksheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount+2, colCount]);
        //    range.Value2 = objData;
        //    System.Windows.Forms.Application.DoEvents();

        //    //***************************保存**********************

        //    if (saveFileName != "")
        //    {
        //        try
        //        {
        //            workbook.Saved = true;
        //            workbook.SaveCopyAs(saveFileName);
        //            fileSaved = true;
        //        }
        //        catch (Exception ex)
        //        {
        //            fileSaved = false;
        //            MessageBox.Show("导出文件时出错,文件可能正被打开！\n" + ex.Message);
        //        }
        //    }
        //    else
        //    {
        //        fileSaved = false;
        //    }
        //    xlApp.Quit();
        //    GC.Collect();//强行销毁   

        //    TimeSpan dateEnd = new TimeSpan(DateTime.Now.Ticks);
        //    TimeSpan tspan = dateBegin.Subtract(dateEnd).Duration();
        //    MessageBox.Show("导出成功，用时" + tspan.ToString() + "秒");
        //    if (fileSaved && System.IO.File.Exists(saveFileName))
        //        System.Diagnostics.Process.Start(saveFileName); //保存成功后打开此文件
        //}
        #endregion
    }
}
